<?php

namespace Mobile\Controller;

/**
 * Description of CustomerController.class控制器实例
 *
 * @author zhangzhen
 * @date 2017-02-14
 */
class CustomerController extends ParentController {

    protected function _initialize() {
        parent::_initialize();
        $this->validateUtil = new \Org\Util\Validate();
    }
    /**
     * 获取客栈客人信息
     * @modify zhangzhen 2017-02-14    创建
     */
    public function customer() {
        $param = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'hotel' => 'notnull,notempty,id'
        );
        $validateResult = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (!$validateResult) {
            $error = true;
        }

        if (!$error) {
            $userId = $param['userId'];
            $token = $param['token'];
            $this->checkMobileToken($userId, $token);
        }

        $hotelId = $param['hotel'];
        $startDate = $param['start'];
        $startDate = empty($startDate) ? date('Y-m-01') : $startDate;
        $endDate = $param['end'];
        $endDate = empty($endDate) ? date('Y-m-d H:i:s') : $endDate . ' 23:59:59';

        $startTime = strtotime($startDate);
        $endTime = strtotime($endDate);

        // 校验是否有操作权限
        $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic');
        $hasRight = $adminAuthorityLogic->check($hotelId);
        if (!$hasRight) {
            returnJson(403, 202);
            return;
        }
        
        // 最多只能查询30天
        if (getTimeDiff($startTime, $endTime, 'day') >= 30) {
            $endDate = date('Y-m-d H:i:s', strtotime('+30 days', $startTime));
        }
        // 获取信息
        $keys = isset($param['keys']) ? $param['keys'] : null;
        $pageIndex = isset($param['currentPage']) ? $param['currentPage'] : 1;

        $customerLogic = A('Common/Customer', 'Logic');
        $customerInfos = $customerLogic->getCustomerInfos($hotelId, $keys, $pageIndex, C('PAGE_SIZE'), null, $startDate, $endDate, 1);
        if (!empty($customerInfos['item'])) {
            // 获取客栈会员信息  补充会员信息
            $vipUserModel = D('VipUser');
            $vipInfo = $vipUserModel->getVipsByHotel($hotelId, null, null, null, null, null);
            foreach ($customerInfos['item'] as $key => &$customerItem) {
                foreach ($vipInfo as $key => $vipItem) {
                    if ($customerItem['mobile'] == $vipItem['mobile'] && $customerItem['areaCode'] == $vipItem['areacode']) {
                        $customerItem['vipname'] = $vipItem['vipname'];
                    }
                }
                unset($vipItem);
            }
            unset($customerItem);
        }
        unset($customerInfos['page']);

        returnJson(200, 200, $customerInfos['item']);
    }
}
